<template>
  <div v-if="!printShow">
    <div class="front">
      <el-collapse v-model="activeNames" class="front-collapse"
        @change="activeNames = !activeNames; collapseName == '收起' ? collapseName = '展开' : collapseName = '收起'">
        <el-collapse-item :title="collapseName" class="collapse-1" name="1">
          <el-form :model="searchForm" label-width="120px">
            <el-form-item label="条码号" class="front-input">
              <el-input v-model="searchForm.barcode" />
            </el-form-item>
            <el-form-item label="调整单id" class="front-input">
              <el-input v-model="searchForm.checkOrderId" />
            </el-form-item>
            <el-form-item label="调整人员" class="front-input">
              <el-select v-model="searchForm.createById" placeholder="选择调整人员" @change="handleWarehouseChange">
                <el-option v-for="employee in employeeList" :key="employee.createById" :value="employee.createById" :label="employee.createBy"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="调整人员id" class="front-input">
              <div class="block">
                <el-date-picker
                  v-model="timeRange"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期时间"
                  end-placeholder="结束日期时间"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="选择日期时间范围"
                />
              </div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSearch">查询</el-button>
              <el-button type="primary" @click="onReset">重置</el-button>
            </el-form-item>
          </el-form>
        </el-collapse-item>
      </el-collapse>
    </div>

    <div class="tail">
      <div class="tail-action">
        <el-button 
          type="primary" 
          plain
          icon="Plus"
          size="mini" 
          @click="handleAdd"
          >新增库存调整单</el-button>
        <el-button type="primary">导出明细</el-button>
        <el-button type="primary" @click="printSelectedRows">打印明细</el-button>
        <el-popover placement="bottom" trigger="click">
          <template #reference>
            <el-button><el-icon>
                <List />
              </el-icon>显示设置</el-button>
          </template>
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
          <el-checkbox-group v-model="selectedFilters" @change="handleCheckChange">
            <el-checkbox v-for="item in tableFilter.map(i => i.label)" :label="item" :key="item" />
          </el-checkbox-group>
        </el-popover>
      </div>
      <el-table :data="tableData()" border style="width: 100%" :max-height="collapseName == '收起' ? 450 : 660" v-loading="tableLoading" @selection-change="handleChangeSelection">
        <template v-slot:empty>
          <div class="no-data">暂无数据</div>
        </template>
        <el-table-column type="selection" width="40" />
        <el-table-column v-for="item in inboundDataColumn" :prop="item.prop" :min-width="item.minWidth" :width="item.width"
          :max-width="item.maxWidth" :label="item.label">
          <!-- <template v-if="true" v-slot:default="scope">
            <div v-if="item.prop == 'orderType'">
              <el-tag v-if="scope.row[item.prop] == 0" type="success">采购入库</el-tag>
              <el-tag v-else-if="scope.row[item.prop] == 1" type="info">借货入库</el-tag>
            </div>
            <span v-else>{{ scope.row[item.prop] }}</span>
          </template> -->
        </el-table-column>
        <el-table-column label="操作" width="80" fixed="right">
          <template #default="scope">
            <el-button link type="danger" size="small" @click="check(scope.row)">查看明细</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination" style="float: right; margin-top: 15px;">
        <el-pagination v-model:current-page="data.page" v-model:page-size="data.limit"
          layout="prev, pager, next ,total,sizes" v-model:total="data.total" @current-change="handleCurrentChange"
          @size-change="handleSizeChange" />
      </div>
    </div>
  </div>
  <div v-else>
    <a-button @click="printShow = false" type="primary" danger>退出打印页面</a-button>
    <print :provider="providerData" :printData="printDataProp"></print>
  </div>
</template>
    
<script>
import { defineComponent, reactive, toRefs, ref } from "vue";
import '@/mock/inbound.js'
import { onMounted, onBeforeMount } from "vue";
import { ElMessage } from "element-plus";
import { getAuditOrder, getEmployee } from '@/api/inbound/inbound'
import { getWarehouseListV2 } from '@/api/setting/setting';
import { getSupplierList } from "@/api/user/user"
import { List } from '@element-plus/icons-vue';
import { useRoute, useRouter } from "vue-router"
import { useStore } from 'vuex';
export default defineComponent({
  name: "HomeView",
  components: {
    List
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const store = useStore()

    const employeeList = ref([])// 调整人员
    const timeRange = ref([])// 时间选择器
    const rowDetails = ref({})
    const drawer = ref(false)
    const isIndeterminate = ref(false)
    const checkAll = ref(true)//显示设置是否全选
    const searchForm = reactive({  //入库查询表单数据
      barcode: null,
      checkOrderId: null,
      createById: null,
      startTime: null,
      endTime: null,
    })
    const inboundJadeData = ref([])
    const selectedFilters = ref([])
    const selectedRows = ref([])//已勾选记录
    const inboundDataColumn = ref([])//表头数据
    const supplierList = ref([])
    const warehouseList = ref([])
    const tableFilter = ref([
      { label: 'id', prop: 'id', width: '100', isdisabled: true, isSelected: true },
      { label: '修改后数量', prop: 'newNum', width: '100', isdisabled: true, isSelected: true },
      { label: '调整单编码', prop: 'orderCode', width: '100', isdisabled: true, isSelected: true },
      { label: '原数量', prop: 'oriNum', width: '100', isdisabled: true, isSelected: true },
      { label: '增加数量', prop: 'profitNum', width: '100', isdisabled: true, isSelected: true },
      { label: '减少数量', prop: 'deficitNum', width: '100', isdisabled: true, isSelected: true },
      { label: '备注', prop: 'remark', width: '200', isdisabled: true, isSelected: true },
      { label: '入库人员', prop: 'createBy', width: '100', isdisabled: true, isSelected: true },
      { label: '入库时间', prop: 'createTime', width: '200', isdisabled: true, isSelected: true },
      { label: '更新时间', prop: 'updateTime', width: '200', isdisabled: true, isSelected: true },
      // { label: '入库单编号', prop: 'inboundOrderCode', width: '120', isdisabled: true, isSelected: true },
      // { label: '入库类型', prop: 'orderType', width: '120', isdisabled: true, isSelected: true },
      // { label: '仓库编码', prop: 'warehouseCode', width: '120', isdisabled: true, isSelected: true },
      // { label: '仓库名称', prop: 'warehouseName', width: '120', isdisabled: true, isSelected: true },
      // { label: '入库仓位编码', prop: 'storageCode', width: '140', isdisabled: true, isSelected: true },
      // { label: '入库仓位名称', prop: 'storageName', width: '140', isdisabled: true, isSelected: true },
      // { label: '翡翠信息ID', prop: 'jadeId', width: '100', isdisabled: true, isSelected: true },
      // { label: '翡翠品类ID', prop: 'jadeTypeId', width: '100', isdisabled: true, isSelected: true },
      // { label: '翡翠品类', prop: 'jadeTypeName', width: '140', isdisabled: true, isSelected: true },
      // { label: '翡翠编码', prop: 'checkOrderId', width: '140', isdisabled: true, isSelected: true },
      // { label: '翡翠名称', prop: 'jadeName', width: '130', isdisabled: true, isSelected: true },
      // { label: '翡翠条码', prop: 'jadeBarcode', width: '130', isdisabled: true, isSelected: true },
      // { label: '成本价格', prop: 'jadeCost', width: '100', isdisabled: true, isSelected: true },
      // { label: '标签价格', prop: 'jadeTagPrice', width: '100', isdisabled: true, isSelected: true },
      // { label: '成本价暗码', prop: 'jadeCostCipher', width: '100', isdisabled: true, isSelected: true },
      // { label: '标签价暗码', prop: 'jadeTagPriceCipher', width: '100', isdisabled: true, isSelected: true },
      // { label: '翡翠图片ID', prop: 'imageId', width: '100', isdisabled: true, isSelected: true },
    ])

    const collapseName = ref('展开');
    const activeNames = ref(false)

    //分页处理
    const state = reactive({//表格用到的参数
      data: {
        page: 1,
        limit: 10,
        total: inboundJadeData.value.length,
      }
    });

    // loading
    const tableLoading = ref(true)
    const tableData = () => {
      // console.log("inboundJadeData:",inboundJadeData)
      return inboundJadeData.value
    };
    const handleCurrentChange = (e) => {//改变页码
      state.data.page = e;
      handleGetInboundOrderList(e, state.data.limit)
    };
    const handleSizeChange = (e) => {//改变页数限制
      state.data.limit = e;
      handleGetInboundOrderList(state.data.page, e)
    };

    const handleGetInboundOrderList = (page, limit) => {//获取入库单列表
      tableLoading.value = true
      const params = {
        pageNum: page,
        pageSize: limit,
        barcode: null,
        checkOrderId: null,
        createById: null,
        startTime: null,
        endTime: null
      }
      // console.log(params)
      getAuditOrder(params).then((res) => {
        // console.log("getAuditOrder:",res)
        inboundJadeData.value = res.rows
        state.data.total = res.total
        tableLoading.value = false
      })
    }
    const handleCheckAllChange = (val) => {//全选按钮
      inboundDataColumn.value = []
      selectedFilters.value = []
      isIndeterminate.value = false;
      if (val) {
        tableFilter.value.forEach(item => {
          item.isSelected = val
          inboundDataColumn.value.push(item)
          selectedFilters.value.push(item.label)
        })
      }

    }
    const handleCheckChange = (val) => {//勾选列
      let temp = []
      tableFilter.value.forEach(item_t => {
        selectedFilters.value.forEach(item_s => {
          if (item_t.label == item_s) {
            temp.push(item_t)
          }
        })
      })
      if (temp.length < tableFilter.value.length && temp.length > 0) {
        isIndeterminate.value = true
      } else {
        isIndeterminate.value = false
      }
      inboundDataColumn.value = temp
      selectedFilters.value = inboundDataColumn.value.map(item => item.label)
    }

    onBeforeMount(() => {
      getSupplierList().then((res) => {
        supplierList.value = res.rows
      })
      getWarehouseListV2().then((res) => {
        warehouseList.value = res
      })
      getEmployee().then((res)=>{// 获取调整人员的id
        employeeList.value = res.data
        console.log("employeeList:",employeeList)
      })
      handleGetInboundOrderList(state.data.page, state.data.limit)
    })

    /** 新增按钮操作 */
    const handleAdd = async() => {
      // 创建新的路由配置
      const newRoute = {
        path: '/edit',
        name: 'Edit',
        component: () => import('@/views/inbound/audits/edit.vue'),
        meta: {
          keepAlive: true,
          title: "新增库存调整单",
          isDynamic: true, // 添加标志
        } 
      };
      // 添加路由到路由器
      router.addRoute(newRoute);
      const newTag = {
        path: '/edit',
        title: '新增库存调整单'
      };
      router.push({ path: newTag.path});
      store.commit('addTag', newTag);
    }
    /** 查看盘点操作 */
    const check = async(rows) => {
      // 创建新的路由配置
      const newRoute = {
        path: '/check',
        name: 'Check',
        component: () => import('@/views/inbound/audits/check.vue'),
        meta: {
          keepAlive: true,
          title: "查看库存调整单",
          isDynamic: true,
          query: rows
        } 
      };
      // 添加路由到路由器
      router.addRoute(newRoute);
      const newTag = {
        path: '/check',
        title: '查看库存调整单',
        query: rows
      };
      // 跳转并传递查询参数
      // router.push({ path: newTag.path, query: { id: 123, name: 'test' } });
      router.push({ path: newTag.path, query: rows});
      store.commit('addTag', newTag);
      
    }

    const printSelectedRows = () => {//打印入库单货品明细
      if (selectedRows.value.length == 0) {
        ElMessage.warning('请选择要打印的记录')
      } else {
        const printWindow = window.open('', '_blank');
        let content = `<html><head><title>打印</title></head><body>`
        content += `<h1>入库货品明细</h1>`
        content += `<table style="border-collapse: collapse; width: 100%;">`;
        content += `<tr>
            <th style="border: 1px solid black; padding: 8px;">入库单单号</th>
            <th style="border: 1px solid black; padding: 8px;">数量</th>
            <th style="border: 1px solid black; padding: 8px;">入库时间</th>
            <th style="border: 1px solid black; padding: 8px;">供应商</th>
            <th style="border: 1px solid black; padding: 8px;">入库仓库</th>
            <th style="border: 1px solid black; padding: 8px;">入库人员</th>
          </tr>`;
        selectedRows.value.forEach(row => {
          content += `<tr>
              <td style="border: 1px solid black; padding: 8px;">${row.orderCode}</td>
              <td style="border: 1px solid black; padding: 8px;">${row.jadeQuantity}</td>
              <td style="border: 1px solid black; padding: 8px;">${row.createTime}</td>
              <td style="border: 1px solid black; padding: 8px;">${row.supplierName}</td>
              <td style="border: 1px solid black; padding: 8px;">${row.warehouseName}</td>
              <td style="border: 1px solid black; padding: 8px;">${row.createBy}</td>
            </tr>`;
        });
        content += `</table></body></html>`;
        printWindow.document.open();
        printWindow.document.write(content);
        printWindow.print()
        printWindow.onload = () => {
          printWindow.print();
          printWindow.close();
        };
        selectedRows.value = []
      }
    }


    onMounted(() => {
      tableFilter.value.forEach(function (item, index) {
        if (item.isSelected) {
          selectedFilters.value.push(item.label)
          inboundDataColumn.value.push(item)
        }
      })
    })
    const mergeOrder = () => {

    }
    const onSearch = () => {
      const params = {
        pageSize: state.data.limit,
        pageNum: state.data.page,
        barcode: searchForm.barcode,
        checkOrderId: searchForm.checkOrderId,
        createById: searchForm.createById,
        startTime: timeRange.value[0]||null,
        endTime: timeRange.value[1]||null
      }
      console.log(params)
      getAuditOrder(params).then((res) => {
        console.log("getAuditOrder:",res)
        inboundJadeData.value = res.rows
        state.data.total = res.total
        tableLoading.value = false
      })
    }

    const handleChangeSelection = (selection) => {//已勾选的记录
      selectedRows.value = selection
      // console.log(selectedRows)
      createElementTypes(selectedRows._rawValue)
      console.log(printData)
    }
    const onReset=()=>{
      searchForm.checkOrderId=searchForm.barcode=searchForm.createById=searchForm.startTime=''
    }

    return {
      inboundJadeData,employeeList,
      searchForm, rowDetails, drawer,
      collapseName, warehouseList, supplierList,
      activeNames,timeRange,
      inboundDataColumn, selectedFilters, tableFilter, checkAll, isIndeterminate,
      tableData, mergeOrder, printSelectedRows, handleChangeSelection,
      handleCurrentChange, handleSizeChange, handleCheckAllChange, handleCheckChange,
      handleGetInboundOrderList, onSearch,onReset,tableLoading,handleAdd,check,
      ...toRefs(state),
    };
  },
});


</script>
    #F8F8F8
    
<style rel="stylesheet/scss" lang="scss" scoped>
.front {
  background-color: #FFF;
  padding: 10px;

  .front-input {
    width: 320px;
  }
}

.center {
  margin-top: 10px;
  // border-top: 1px solid var(--el-border-color);
  // border-bottom: 1px solid var(--el-border-color);
}

.tail {
  background-color: #FFF;
  margin-top: 10px;
  padding: 10px;
}

.tail-action {
  display: flex;
  margin-bottom: 10px;
}


.center .center-data {
  height: 30px;
  width: 150px;
  border: 1px solid;
  border-radius: 10px;
  margin: 10px;
  text-align: center;
  font-size: 20px;
  background-color: #72f6ff;
}

.el-table {
  .el-button {
    margin-left: 0px; //调整按钮不对齐
  }
}

</style>
    